package com.baibei.module.stock.basic;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.baibei.ebec.sdk.IQuotationApi;
import com.baibei.model.KLineEntry;
import com.baibei.module.LazyLoadFragment;
import com.baibei.module.stock.OnChartGestureListener2;
import com.baibei.module.stock.R;
import com.baibei.module.stock.StockLayout;
import com.baibei.module.stock.theme.KLineChartTheme;
import com.baibei.quotation.event.QuotationPendingEvent;
import com.baibei.widget.stock.KLineChart;
import com.baibei.widget.stock.RaeChartContainer;
import com.baibei.widget.stock.RaeMarkerView;
import com.baibei.widget.stock.listener.OnChartGestureValueChangeListener;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.jobs.MoveViewJob;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.rae.swift.Rx;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

/**
 * K线基础
 * Created by ChenRui on 2017/5/22 0022 9:59.
 */
public class BasicKLineFragment extends LazyLoadFragment implements StockKLineContract.View {


    private TextView mMarkerViewText;
    private View mMALayout;
    private View mChatTypeLayout;
    private TextView mLegendMA5View;
    private TextView mLegendMA10View;
    private TextView mLegendMA20View;

    protected KLineChart mKLineChart;
    //    protected RaeBarChart mVolumeChart;
    protected RaeChartContainer mRaeChartContainer;
    protected String mType;
    private StockLayout mStockLayout;
    private int mPosition = -1;

    private StockKLineContract.Presenter mPresenter;

    private String mProductInfo;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mType = getArguments().getString("type", IQuotationApi.TYPE_KLINE_5);
        mPosition = getArguments().getInt("position");
        mProductInfo = getArguments().getString("productInfo");
        mPresenter = inject(StockKLineContract.Presenter.class);
        EventBus.getDefault().register(this);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mStockLayout = (StockLayout) view.findViewById(R.id.layout_stock);
//        mRaeChartContainer = (RaeChartContainer) view.findViewById(R.id.chart_container);
        mKLineChart = (KLineChart) view.findViewById(R.id.chart_kline);
        mKLineChart.setMinXCount(40);
        mKLineChart.setTheme(new KLineChartTheme());
        mKLineChart.getAxisLeft().setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return Rx.formatPrice(value);
            }
        });
//        mVolumeChart = (RaeBarChart) mRaeChartContainer.getChart(ChartType.VOLUME);

        mMALayout = view.findViewById(R.id.ll_stock_ma_layout);
        mChatTypeLayout = view.findViewById(R.id.ll_stock_indicator_layout);
        mLegendMA5View = (TextView) view.findViewById(R.id.tv_legend_ma5);
        mLegendMA10View = (TextView) view.findViewById(R.id.tv_legend_ma10);
        mLegendMA20View = (TextView) view.findViewById(R.id.tv_legend_ma20);


        mMALayout.setVisibility(View.INVISIBLE);


//        // 空白处点击
//        mStockLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                // 休市前半个小时状态
//                if (ProductProvider.isTradePending()) {
//                    return;
//                }
//                AppRouter.routeToLandscapeChart(getContext(), ChartType.K_LINE.name(), mType);
//            }
//        });

        // 成交量主题
//        mVolumeChart.setTheme(new DefaultKLineVolumeTheme());

        // 分时图标记图
        RaeMarkerView markerView = new RaeMarkerView(getContext(), R.layout.stock_timeline_marker_view, RaeMarkerView.MarkerViewPosition.HORIZONTAL);
        markerView.setIndicatorDrawable(ContextCompat.getDrawable(getContext(), R.drawable.icon_stock_indicator));
        mMarkerViewText = (TextView) markerView.findViewById(R.id.tv_marker_view_text);
        mKLineChart.setDrawMarkers(true);
        mKLineChart.setMarker(markerView);


//        // 设置成交量的图标颜色格式
//        mVolumeChart.setColorRenderFormatter(new VolumeChartRender.IVolumeColorRenderFormatter() {
//            @Override
//            public void onRenderFormat(int position, Paint renderPaint) {
//                CandleEntry entry = mKLineChart.getData().getCandleData().getDataSetByIndex(0).getEntryForIndex(position);
//                int color;
//                Paint.Style style;
//                if (entry.getOpen() > entry.getClose()) {
//                    style = Paint.Style.FILL;
//                    color = ContextCompat.getColor(getContext(), R.color.decreasingColor);
//                } else if (entry.getOpen() < entry.getClose()) {
//                    style = Paint.Style.STROKE;
//                    color = ContextCompat.getColor(getContext(), R.color.increasingColor);
//                } else {
//                    style = Paint.Style.FILL;
//                    color = ContextCompat.getColor(getContext(), R.color.neutralColor);
//                }
//
//                renderPaint.setColor(color);
//                renderPaint.setStyle(style);
//
//            }
//        });

        // 选择
        mKLineChart.addOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                mMarkerViewText.setText(mKLineChart.getAxisLeftLabel(e.getY()));
                onLoadLegendMaValue((int) e.getX());
            }

            @Override
            public void onNothingSelected() {
            }
        });

        mKLineChart.setOnChartGestureValueChangeListener(new OnChartGestureValueChangeListener() {
            @Override
            public void OnChartGestureValueChange(int min, int max) {
                onLoadLegendMaValue(max);
            }
        });

//        mRaeChartContainer.setOnChartChangeListener(new IChartChangeListener() {
//            @Override
//            public void onChartChange(RaeCombinedChart chart, ChartType type) {
//                chart.setMarker(mVolumeChart.getMarker());
//                ChartRelationship.relation(mKLineChart, chart);
//
//            }
//        });
//
//        ChartRelationship.relation(mKLineChart, mVolumeChart);
        if (mOnChartGestureListener != null) {
            mKLineChart.setOnChartGestureListener(new OnChartGestureListener() {
                @Override
                public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
                    if (mOnChartGestureListener != null) {
                        mOnChartGestureListener.onChartGestureStart(mKLineChart, me, lastPerformedGesture);
                    }
                }

                @Override
                public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
                    if (mOnChartGestureListener != null) {
                        mOnChartGestureListener.onChartGestureEnd(mKLineChart, me, lastPerformedGesture);
                    }
                }

                @Override
                public void onChartLongPressed(MotionEvent me) {
                    if (mOnChartGestureListener != null) {
                        mOnChartGestureListener.onChartLongPressed(mKLineChart, me);
                    }
                }

                @Override
                public void onChartDoubleTapped(MotionEvent me) {

                }

                @Override
                public void onChartSingleTapped(MotionEvent me) {

                }

                @Override
                public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

                }

                @Override
                public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

                }

                @Override
                public void onChartTranslate(MotionEvent me, float dX, float dY) {

                }
            });
        }
    }

    /**
     * 监听手势回调
     */
    private OnChartGestureListener2 mOnChartGestureListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnChartGestureListener2) {
            mOnChartGestureListener = (OnChartGestureListener2) context;
        }
    }

    /**
     * 加载移动平均线的值
     */
    protected void onLoadLegendMaValue(int position) {

        LineData lineData = mKLineChart.getLineData();
        int count = lineData.getDataSetCount();
        if (count > 0 && lineData.getDataSetByIndex(0).getEntryCount() > position) {
            float ma5 = lineData.getDataSetByIndex(0).getEntryForIndex(position).getY();
            setLegendText(mLegendMA5View, "MA5 ", ma5);
        }
        if (count > 1 && lineData.getDataSetByIndex(1).getEntryCount() > position) {
            float ma10 = lineData.getDataSetByIndex(1).getEntryForIndex(position).getY();
            setLegendText(mLegendMA10View, "MA10 ", ma10);
        }
        if (count > 2 && lineData.getDataSetByIndex(2).getEntryCount() > position) {
            float ma20 = lineData.getDataSetByIndex(2).getEntryForIndex(position).getY();
            setLegendText(mLegendMA20View, "MA20 ", ma20);
        }
    }


    private void setLegendText(TextView view, String prefix, float value) {
        if (!isAdded()) return;
        if (Float.isNaN(value)) {
            view.setText(prefix + getString(R.string.default_placeholder));
        } else {
            view.setText(String.format("%s%.2f", prefix, value));
        }
    }

    @Override
    public int getLayoutId(Bundle savedInstanceState) {
        return R.layout.fm_stock_kline_simple;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isInitData) {
            if (isVisibleToUser) {
                mPresenter.registerMarketStatus();
            } else {
                mPresenter.unRegisterMarketStatus();
                mPresenter.stopInterval();
            }
        } else {
            super.setUserVisibleHint(isVisibleToUser);
        }
    }


    @Override
    public void lazyLoad() {
        loadData();
    }

    /**
     * 加载数据
     */
    protected void loadData() {
        // 空的
        if (mType == null) {
            mStockLayout.setEmpty(true);
            return;
        }
        mPresenter.start();
        mStockLayout.showLoading();
        isInitData = true;
    }

    @Override
    public void onLoadKLineData(List<KLineEntry> data) {

        mKLineChart.clear();
//        mVolumeChart.clear();
        if (Rx.isEmpty(data)) {
            mStockLayout.dismissLoading();
            mStockLayout.setEmpty(true);
            return;
        }
        mStockLayout.dismissLoading();
        mStockLayout.setEmpty(false);

        List<CandleEntry> yValues = new ArrayList<>();
        List<String> xValues = new ArrayList<>();
        List<BarEntry> volumeValues = new ArrayList<>();

        @SuppressLint("SimpleDateFormat")
        int count = data.size();
        for (int i = 0; i < count; i++) {
            KLineEntry entry = data.get(i);
            xValues.add(entry.getDay()); // DateUtils.formatDate(entry.getTimeStamp(), "MM-dd")
            yValues.add(new CandleEntry(i, entry.getHigh(), entry.getLow(), entry.getOpen(), entry.getClose()));
            volumeValues.add(new BarEntry(i, entry.getVolume()));
        }

        mKLineChart.setCandleData(xValues, yValues);
//        mVolumeChart.setData(xValues, volumeValues);
//        mVolumeChart.invalidate();


        mMALayout.setVisibility(View.VISIBLE);


//        RaeCombinedChart current = mRaeChartContainer.getCurrentChart();
//
//        // 同步视图大小
//        if (current != null) {
//            CoupleChartGestureListener.sync(mKLineChart, current);
//            float offsetLeft = mKLineChart.getViewPortHandler().offsetLeft();
//            current.setVisibleXRangeMinimum(mKLineChart.getVisibleXRangeMinimum()); // 设置X轴最小显示多少条数据
//            current.setViewPortOffsets(offsetLeft, 0, current.getViewPortHandler().offsetRight(), current.getViewPortHandler().offsetBottom());
//            current.setChartScaleX(mKLineChart.getChartScaleX());
//            current.moveViewToEnd();
//        }

    }

    @Override
    public void onDestroyView() {
        mKLineChart.clear();
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        mPresenter.destroy();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 解决内存溢出
        MoveViewJob.getInstance(null, 0, 0, null, null);
    }

    @Override
    public void onLoadFailed(String message) {
        mStockLayout.dismissLoading();
        mStockLayout.setEmpty(true);
        mKLineChart.setNoDataText(message);
        mKLineChart.clear();
        mKLineChart.invalidate();

//        RaeCombinedChart current = mRaeChartContainer.getCurrentChart();
//        if (current != null) {
//            current.setNoDataText("");
//            current.clear();
//            current.invalidate();
//        }
    }

    @Override
    public String getType() {
        return mType;
    }

    @Override
    public String getProductId() {
        return mProductInfo;
    }

    @Override
    public void onTradeOutTime() {
        mStockLayout.dismissLoading();
        mStockLayout.setEmpty(false);
        mKLineChart.setNoDataTextSize(20);
        mKLineChart.setNoDataText("休市中");
        mKLineChart.clear();

        mMALayout.setVisibility(View.GONE);
    }

    @Override
    public void onTradeOpenTime() {

    }

//    /**
//     * 重新加载数据
//     *
//     * @param type
//     */
//    public void reload(String type) {
//        if (getArguments() == null) {
//            setArguments(new Bundle());
//        }
//
//        getArguments().putString("type", type);
//
//        mType = type;
//
//
//        if (mKLineChart != null) {
//            mKLineChart.clear();
//        }
//        if (mRaeChartContainer != null) {
//            mRaeChartC  loadData(); // 开市重新加载数据ontainer.clearData();
//        }
//        if (mPresenter != null)
//            loadData();
//    }


    @Subscribe
    public void onEvent(QuotationPendingEvent event) {
        mStockLayout.setIsTrade(event.isOpen);
        mMALayout.setVisibility(event.isOpen ? View.VISIBLE : View.GONE);
        if (mChatTypeLayout != null) {
            mChatTypeLayout.setVisibility(event.isOpen ? View.VISIBLE : View.GONE);
        }
        if (event.isOpen) {

        }
    }

}